
import { globalUtils } from '../../common/js/global-utils/global-utils-all';
import { uiUtils } from '../../common/js/ui-utils/ui-utils-all';
import Pure from 'pure-frontend';
import uiData from 'ui-data';

/* SOURCE-CODE-START */

"use strict";


Pure.app.viewMain('permission-management', function (scope, view) {
  var model = view.getDataModel();
  var jqTable = view.$ui('permissionTable');
  var jqCreateBtn = view.$ui('createBtn');
  var jqSearchBtn = view.$ui('searchBtn');
  var jqNewPermissionDialog = view.$ui('newPermissionDialog');
  var jqEditPermissionDialog = view.$ui('editPermissionDialog');
  var jqNewPermissionForm = jqNewPermissionDialog.find('form');
  var jqEditPermissionForm = jqEditPermissionDialog.find('form');

  //
  // 表格
  //

  // 初始表格
  uiUtils.dataGrid.init(jqTable, {
    url: 'api/security/permission/pagePermissionsByCond',
    columns: [
      {
        field: 'id'
      },
      {
        field: 'permissionCode'
      },
      {
        field: 'permissionName'
      },
      {
        field: 'remark'
      },
      {
        field: 'operate',
        'class': 'x-nowrap-items',
        formatter: formatOprationColumn,
        events: {
          'click .delete': clickDeleteOperationFn,
          'click .edit': clickEditOperationFn,
          'click .assignResource': clickAssignResourceOperationFn
        }
      }
    ]
  });

  function formatOprationColumn(value, row, index) {
    return [
      '<a class="edit" href="javascript:void(0)">',
      '<span>${t("ui.system.common.operation.edit")}</span>',
      '</a>',
      '&nbsp;',
      '<a class="delete" href="javascript:void(0)">',
      '<span>${t("ui.system.common.operation.delete")}</span>',
      '</a>',
      '&nbsp;',
      '<a class="assignResource" href="javascript:void(0)">',
      '<span>${t("ui.security.permission.operation.assignResource")}</span>',
      '</a>'
    ].join('');
  }

  jqSearchBtn.on(uiUtils.event.CLICK, function () {
    var data = model.getData('searchField.*');
    data = uiData.utils.unprefix(data, 'searchField.');

    uiUtils.dataGrid.newQuery(jqTable, {
      customQuery: data
    });
  });

  // 点击创建按钮的事件
  jqCreateBtn.on('click', function () {
    // 显示弹出框
    uiUtils.dialog.showModal(jqNewPermissionDialog, {
      backdropParent: view.getViewElement(),
      onModalHide: function () {
        uiUtils.common.resetValidation(jqNewPermissionForm);
      }
    });

    // 离开页面时检查是否表单发生变更
    uiUtils.view.setCurrentFormDataToContext(scope, getNewData);
    uiUtils.view.checkFormDataChangeWhenLeave(scope, getNewData);
  });

  var permissionValidationRule = {
    rules: {
      permissionCode: {
        required: true,
        maxlength: 50,
        customCode: true
      },
      permissionName: {
        required: true,
        maxlength: 20
      },
      remark: {
        maxlength: 200
      }
    },
    messages: {
      permissionCode: {
        required: '${t("ui.security.permission.validation.permissionCodeRequired")}'
      },
      permissionName: {
        required: '${t("ui.security.permission.validation.permissionNameRequired")}'
      }
    }
  };

  //
  // "新建权限"弹出框
  //

  // 定义新建记录的校验规则
  jqNewPermissionForm.validate(permissionValidationRule);

  // 点击"新建权限"弹出框的保存按钮
  jqNewPermissionDialog.on('click', '.x-btn-confirm', function () {
    var checkResult = jqNewPermissionForm.valid();
    if (!checkResult) {
      return;
    }

    var data = model.getData('new.*');
    data = uiData.utils.unprefix(data, 'new.');

    // 调用保存记录的接口
    view.callService('api/security/permission/savePermission', data)
      .waitResult(function (saveResult) {
        if (!uiUtils.common.checkWebResultSuccess(saveResult)) {
          return;
        }

        uiUtils.dialog.hideModal(jqNewPermissionDialog);
        Pure.app.showMessage('${t("ui.system.common.msg.saveRecordSuccess")}');
        uiUtils.dataGrid.refresh(jqTable);
      });
  });

  jqNewPermissionDialog.on('hide.bs.modal', function () {
    uiUtils.view.notCheckFormDataChangeWhenLeave(scope);
  });

  function getNewData() {
    return model.getData('new.*');
  }


  //
  // "编辑权限"弹出框
  //

  // 定义编辑记录的校验规则
  jqEditPermissionForm.validate(permissionValidationRule);

  // 点击"编辑权限"弹出框的保存按钮
  jqEditPermissionDialog.on('click', '.x-btn-confirm', function () {
    var checkResult = jqEditPermissionForm.valid();
    if (!checkResult) {
      return;
    }

    var data = model.getData('edit.*');
    data = uiData.utils.unprefix(data, 'edit.', true);

    // 调用更新记录的接口
    view.callService('api/security/permission/updatePermission', data)
      .waitResult(function (result) {
        if (result.success) {
          uiUtils.dialog.hideModal(jqEditPermissionDialog);
          Pure.app.showMessage('${t("ui.system.common.msg.saveRecordSuccess")}');
          uiUtils.dataGrid.refresh(jqTable);
        } else {
          Pure.app.showError(result.message);
        }
      });
  });

  jqEditPermissionDialog.on('hide.bs.modal', function () {
    uiUtils.view.notCheckFormDataChangeWhenLeave(scope);
  });


  function getEditData() {
    return model.getData('edit.*');
  }


  //
  //
  //

  /**
   * 点击编辑的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickEditOperationFn(e, value, row, index) {
    uiUtils.dialog.showModal(jqEditPermissionDialog, {
      backdropParent: view.getViewElement(),
      onModalHide: function () {
        uiUtils.common.resetValidation(jqEditPermissionForm);
      }
    });

    var queryParams = {
      id: row.id
    };

    // 调用接口获取记录
    view.callService('api/security/permission/getPermissionById', queryParams)
      .waitResult(function (result, textStatus, jqXHR) {
        if (!uiUtils.common.checkWebResultSuccess(result)) {
          return;
        }

        var data = uiData.utils.prefix(result.data, 'edit.');
        model.setData('edit.*', data);

        // 离开页面时检查是否表单发生变更
        uiUtils.view.setCurrentFormDataToContext(scope, getEditData);
        uiUtils.view.checkFormDataChangeWhenLeave(scope, getEditData);
      });
  }

  /**
   * 点击删除的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickDeleteOperationFn(e, value, row, index) {
    var data = {
      id: row.id
    };

    uiUtils.dialog.showConfirmBox('${t("ui.system.common.msg.confirmDeleteReocrd")}', function () {
      // 调用删除记录的接口
      view.callService('api/security/permission/deletePermissionById', data)
        .waitResult(function (result, textStatus, jqXHR) {
          if (result.success) {
            Pure.app.showMessage('${t("ui.system.common.msg.deleteRecordSuccess")}');
            // 刷新表格
            uiUtils.dataGrid.refresh(jqTable);
          } else {
            Pure.app.showError(result.message);
          }
        });
    });
  }

  /**
   * 点击分配资源的事件
   * @param {*} e 
   * @param {*} value 
   * @param {*} row 
   * @param {*} index 
   */
  function clickAssignResourceOperationFn(e, value, row, index) {
    scope.showAssignResourceDialog(view, row.id);
  }

});

/* SOURCE-CODE-END */
